package cn.edu.zstu.qingzhu.qingzhushop.service.impl;

import cn.edu.zstu.qingzhu.qingzhushop.common.ResponseBeanMessage;
import cn.edu.zstu.qingzhu.qingzhushop.entity.*;
import cn.edu.zstu.qingzhu.qingzhushop.mapper.GoodsMapper;
import cn.edu.zstu.qingzhu.qingzhushop.mapper.OrderDetailMapper;
import cn.edu.zstu.qingzhu.qingzhushop.mapper.OrderMapper;
import cn.edu.zstu.qingzhu.qingzhushop.rabbitmq.publisher.DeadPublisher;
import cn.edu.zstu.qingzhu.qingzhushop.service.IOrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
        implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    DeadPublisher deadPublisher;

    @Override
    public Order selectByOrderId(Integer id) {
        return orderMapper.selectByOrderId(id);
    }

    @Override
    public List<Order> selectByOrderCode(String orderCode) {
        return orderMapper.selectByOrderCode(orderCode);
    }

    @Override
    public int updateByIdSelective(Order order) {
        return orderMapper.updateByIdSelective(order);
    }

    @Override
    public List<Order> selectByUserId(Integer userId) {
        return orderMapper.selectByUserId(userId);
    }

    @Override
    public OrderDetail getOrderDetailByOrderNo(String orderNo, Integer id) {
        return null;
    }

    @Override
    public Page<Order> listOrderByUserId(Integer id, Integer page, Integer size) {
        return orderMapper.selectPage(new Page<>(page, size), new QueryWrapper<>());
    }

    @Override
    @Transactional
    public Object saveOrder(AuthenticationUser user, List<ShoppingCart> shoppingCartList) {
        return null;
    }

    @Override
    public String cancelOrder(String orderNo, Integer id) {
        return null;
    }

    @Override
    public String finishOrder(String orderNo, Integer id) {
        return "success";
    }

    @Override
    public String paySuccess(String orderNo, int payType) {
        return null;
    }




    /**
     * 新建订单
     *
     * @param order 用户
     * @param goods goods
     * @return
     */
    @Override
    @Transactional
    public Integer submitOrder(Order order, List<Integer> goods) {
        BigDecimal priceTotal = new BigDecimal(0);
        List<Goods> list = new ArrayList<>();
        for (Integer i :goods){
            list.add(goodsMapper.selectByGoodsId(i));
        }
        for (Goods shop : list) {
            //总价
            priceTotal = priceTotal.add(shop.getGoodsPrice());
        }
        if (priceTotal.compareTo(new BigDecimal(0)) < 0) {
            throw new RuntimeException(ResponseBeanMessage.ORDER_PRICE_ERROR);
        }
        order.setAmount(priceTotal.toString());
        orderMapper.insert(order);
        Integer id = order.getId();
        for (Goods shop : list) {
            OrderDetail detail = new OrderDetail();
            detail.setOrderId(id);
            detail.setGoodsId(shop.getId());
            detail.setShoppingCartId(null);
            detail.setDiscount("1");
            detail.setTotalPrice(shop.getGoodsPrice());
            detail.setMessage(order.getMessage());
            detail.setSortNum((list.indexOf(shop)));
            detail.setCreateTime(LocalDateTime.now());
            detail.setUpdateTime(LocalDateTime.now());
            orderDetailMapper.insert(detail);
        }
        deadPublisher.sendMsg(id.toString());
        return id;
    }

    @Override
    public String sumSalesVolume() {
        return String.valueOf(orderMapper.selectSumSalesVolume());
    }

    @Override
    public String sumSales() {
        return orderMapper.selectSumSales().toString();
    }

    @Override
    @Transactional
    public int paySuccess(Integer orderId) throws Exception {
        Order order = orderMapper.selectByOrderIdForUpdate(orderId);
        if (order.getStatus().equals("已超时")){
            return 3;
        }else if (order.getStatus().equals("已付款")){
            return 2;
        }else if (order.getStatus().equals("未付款")){
            order.setStatus("已付款");
            QueryWrapper wrapper = new QueryWrapper();
            Map<String,Object> map = new HashMap<>();
            map.put("status","未付款");
            map.put("id",order.getId());
            wrapper.allEq(map);
            int i = orderMapper.update(order,wrapper);
            System.out.println(i);
            if (i==0){
                return 3;
            }else{
                return 1;
            }
        }
        return 0;
    }

    @Override
    public Order getById(Serializable id) {
        assert id instanceof Integer;
        return orderMapper.selectByOrderId((Integer) id);
    }
}
